package com.slfx.idgen.demo.idgen.uuid;

import org.springframework.beans.factory.InitializingBean;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CachedUUIDGenerator implements UUIDGeneratorInterface, InitializingBean {

    private LinkedBlockingQueue<String> idQueue;

    private Long maxSize;

    private Long minSize=100000L;

    private boolean isActive = true;

    public CachedUUIDGenerator(Long maxSize) {
        if (maxSize == null || maxSize< minSize){
            maxSize = minSize;
        }
        this.idQueue = new LinkedBlockingQueue<>();
        this.maxSize = maxSize;
    }

    @Override
    public String getNextUUID() {
        String id = "";
        try {
            id = idQueue.take();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return id;
    }

    @Override
    public void afterPropertiesSet() {
        int cores = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(cores, cores, 0,
                TimeUnit.NANOSECONDS, new ArrayBlockingQueue<>(10000), r -> {
            Thread thread = new Thread(r);
            thread.setName("uuidGenerator");
            return thread;
        });

        threadPoolExecutor.execute(this::putId);
    }

    private void putId() {
        while (isActive) {
            if (idQueue.size() < maxSize) {
                try {
                    idQueue.put(defaultUUID());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }


}
